import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn.metrics import silhouette_score
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.metrics import silhouette_score
from matplotlib import font_manager


my_font = font_manager.FontProperties(fname="/Windows/Fonts/simhei.ttf",size=20)
import matplotlib.pyplot as plt


df_features = pd.read_excel(r'beijing.xlsx')  # 读入数据
print(df_features.info)
X=df_features[['area', 'unit_price', 'total_price']]
'利用SSE选择k'
SSE = []  # 存放每次结果的误差平方和
for k in range(1, 18):
    estimator = KMeans(n_clusters=k)  # 构造聚类器
    estimator.fit(df_features[['area', 'unit_price', 'total_price']])
    SSE.append(estimator.inertia_)  # estimator.inertia_获取聚类准则的总和
X = range(1, 18)
plt.xlabel('k')
plt.ylabel('SSE')
plt.plot(X, SSE, 'o-')
plt.savefig('SSE.jpg')
plt.show()
Scores = []
for k in range(2,18):
    estimator = KMeans(n_clusters=k)
    estimator.fit(df_features[['area', 'unit_price', 'total_price']])
    labels = estimator.fit(df_features[['area', 'unit_price', 'total_price']]).labels_
    Scores.append(silhouette_score(df_features[['area', 'unit_price', 'total_price']],labels,metric='euclidean'))
X = range(2,18)
plt.xlabel('k值——簇数量',fontproperties=my_font,size=20)
plt.ylabel('轮廓系数',fontproperties=my_font,size=20)
plt.plot(X,Scores,'o-')
plt.savefig('轮廓系数.jpg')
plt.show()


